<template>
  <div class="cont">
    <div class="dia">
      <div class="header">
        <div class="title">
          <el-icon :size="20" style="margin-right: 10px"
            ><RefreshRight
          /></el-icon>
          全景回放
        </div>
        <div class="close" @click="emit('close')"></div>
      </div>
      <div class="content">
        <div
          class="full"
          :id="state.pid"
          style="width: 100%; height: 100%"
        ></div>
        <div class="chvBox">
          <div
            class="chv-container"
            v-for="(item, index) in state.pm.lowCameraIds"
            :key="index"
          >
            <onebk ref="them" :vid="item" class="chv-item" />
          </div>
        </div>
      </div>
      <div class="foot">
        <div class="prog">
          <el-slider
            v-model="state.ctime"
            :format-tooltip="ftip"
            :max="state.max"
            @change="timechange"
          />
        </div>
        <div class="botom">
          <img class="img" src="/images/full.png" @click="fullv" />
          <img class="img" src="/images/paiz.png" @click="crop" />
          <img
            class="img"
            src="/images/down.png"
            :style="state.isv ? 'background-color:red;' : ''"
            :title="state.isv ? '视频录制中' : ''"
            @click="torec"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";

const emit = defineEmits(["close"]);
const them = ref();
const state = reactive({
  pm: {},
  vid: "",
  cid: "",
  myPlugin: null,
  curIndex: 0,
  pid: "p" + Math.floor(Math.random() * 1000) + 1,
  max: 100,
  beginTime: null,
  endTime: null,
  ctime: 0,

  isv: false,
});
const ftip = (val) => {
  let dt = new Date(state.pm.beginTime);
  let min = dt.getMinutes();
  dt.setMinutes(min + val);
  return dateFormat(dt, "HH:mm");
};
const timechange = (val) => {
  let dt = new Date(state.pm.beginTime);
  let min = dt.getMinutes();
  dt.setMinutes(min + val);

  let bt = dateFormat(dt, "YYYY-MM-DDTHH:mm:ss") + ".000+08:00";
  let et =
    dateFormat(new Date(state.pm.endTime), "YYYY-MM-DDTHH:mm:ss") +
    ".000+08:00";

  if (state.myPlugin) {
    play(bt, et);
    them.value.seek(bt);
    // state.myPlugin.JS_Seek(state.curIndex, bt, et).then(
    //   () => {
    //     console.info("JS_Seek success");
    //     them.value.seek(bt)
    //   },
    //   (err) => {
    //     ElMessage.success("定位失败,错误码：" + err);
    //   }
    // );
  }
};
const fullv = () => {
  state.myPlugin.JS_FullScreenDisplay(true);
};
const crop = () => {
  let fileName = "img";
  let fileType = "JPEG";
  state.myPlugin.JS_CapturePicture(state.curIndex, fileName, fileType).then(
    () => {
      ElMessage.success("截图成功,请查看下载");
    },
    (err) => {
      ElMessage.success("截图失败,错误码：" + err);
    }
  );
};
const torec = () => {
  if (state.isv == false) {
    startv();
  } else {
    endv();
  }
};
const startv = () => {
  let fileName = new Date().getTime() + ".mp4";
  state.myPlugin.JS_StartSaveEx(state.curIndex, fileName, 5).then(
    () => {
      state.isv = true;
      ElMessage.success("已开始录像");
    },
    (err) => {
      //console.log("JS_CapturePicture failed",err);
      ElMessage.success("开始录像,错误码：" + err);
    }
  );
};
const endv = () => {
  state.myPlugin.JS_StopSave(state.curIndex).then(
    () => {
      state.isv = false;
      ElMessage.success("录像成功,下载时间较长，请耐心等待下载...");
    },
    (err) => {
      //console.log("JS_CapturePicture failed",err);
      ElMessage.success("录像失败,错误码：" + err);
    }
  );
};
const play = (bT, eT) => {
  let bt = bT
    ? bT
    : dateFormat(new Date(state.pm.beginTime), "YYYY-MM-DDTHH:mm:ss") +
      ".000+08:00";
  let et = eT
    ? eT
    : dateFormat(new Date(state.pm.endTime), "YYYY-MM-DDTHH:mm:ss") +
      ".000+08:00";
  let pm = {
    cameraId: state.pm.highCameraId,
    beginTime: bt,
    endTime: et,
    uuid: "",
  };
  //根据选择 获取监控点播放地址，尝试播放
  useApi.post("/dynamicview/ar/getplaybackurls", pm).then((res) => {
    let url = res.data.url || "";
    if (url != "") {
      // state.myPlugin.JS_StopRealPlayAll();
      state.myPlugin.JS_Play(url, { playURL: url, mode: 1 }, 0, bt, et);
    } else {
      ElMessage.error("未获取到播放地址");
    }
  });
};
// const initPlayer = () => {
//   console.log("初始化播放-----------------器", state.pid);
//   if (state.myPlugin != null) return;
//   console.log("初始化播放-----------------sssssssssssss器", state);
//   state.myPlugin = new JSPlugin({
//     szId: state.pid, //需要英文字母开头，唯一性，必填
//     szBasePath: "/js/", // 必填,与h5player.min.js的引用目录一致
//     bSupporDoubleClickFull: true, //是否支持双击全屏，默认true
//     // 分屏播放，默认最大分屏4*4
//     iMaxSplit: 1,
//     iCurrentSplit: 1,
//   });

//   state.myPlugin.JS_SetWindowControlCallback({
//     windowEventSelect: function (index) {
//       //插件选中窗口回调
//       state.curIndex = index;
//     },
//     pluginErrorHandler: function (iWndIndex, iErrorCode, oError) {
//       //插件错误回调
//       console.error(`window-${iWndIndex}, errorCode: ${iErrorCode}`, oError);
//       ElMessage.error(`播放失败, 错误码: ${iErrorCode},正在重新取流`);
//       timechange(state.ctime);
//     },
//   });
// };

const initPlayer = () => {
  if (state.myPlugin) return;

  nextTick().then(() => {
    const playerContainer = document.getElementById(state.pid);
    if (!playerContainer) {
      console.error("播放器容器未找到，ID:", state.pid);
      ElMessage.error("播放器容器未找到");
      return;
    }

    // 确保容器有有效尺寸
    if (playerContainer.clientWidth === 0) {
      console.error("播放器容器宽度为 0，请检查 CSS 样式");
      ElMessage.error("播放器容器尺寸异常");
      return;
    }

    setTimeout(() => {
      try {
        state.myPlugin = new JSPlugin({
          szId: state.pid,
          szBasePath: "/js/",
          bSupporDoubleClickFull: true,
          iMaxSplit: 1,
          iCurrentSplit: 1,
        });

        state.myPlugin.JS_SetWindowControlCallback({
          windowEventSelect: (index) => (state.curIndex = index),
          pluginErrorHandler: (iWndIndex, iErrorCode) => {
            console.error(`窗口 ${iWndIndex} 错误，代码: ${iErrorCode}`);
            ElMessage.error(`播放失败，错误码: ${iErrorCode}`);
            timechange(state.ctime);
          },
        });
      } catch (err) {
        console.error("初始化失败:", err);
        ElMessage.error("播放器初始化失败，请检查控制台");
      }
    }, 100);
  });
};
const destoryPlayer = () => {
  if (state.myPlugin) {
    state.myPlugin.JS_StopRealPlayAll();
    state.myPlugin.JS_DestroyWorker();
    state.myPlugin = null;
  }
};
onMounted(() => {
  let store = useMyStore();
  state.pm = store.params.backpm || {};
  console.log("回放参数", state.pm);
  if (state.pm.highCameraId) {
    //计算时间间隔
    state.beginTime = new Date(state.pm.beginTime);
    state.endTime = new Date(state.pm.endTime);
    let time = state.endTime.getTime() - state.beginTime.getTime();
    time /= 60000;
    state.max = time;
    //初始化
    nextTick(() => {
      console.log("nextTick");
      initPlayer();
      play();
    });
  }
});
//注销时 销毁组件
onBeforeUnmount(() => {
  destoryPlayer();
});
</script>

<style lang="scss" scoped>
.cont {
  width: 1200px;
}

.dia {
  margin-top: 5px;
  width: 1200px;
  height: 800px;
  background-image: url("/images/bgd.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;

  .header {
    width: 1200px;
    height: 38px;

    display: flex;
    align-items: center;

    .title {
      margin-left: 10px;
      font-weight: 600;
      font-size: 14px;
      color: #ffffff;
      display: flex;
      align-items: center;
    }

    .close {
      margin: 8px 2px 0 auto;
      background-image: url("/images/close.png");
      background-size: 100% 100%;
      background-repeat: no-repeat;
      width: 30px;
      height: 30px;
      cursor: pointer;
    }
  }

  .content {
    width: 100%;
    height: 678px;
    position: relative;
  }

  .foot {
    height: 84px;
    display: flex;
    flex-direction: column;

    .prog {
      height: 12px;
      padding: 0 20px;
    }

    .botom {
      height: 72px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-right: 10px;

      .img {
        cursor: pointer;
        width: 36px;
        height: 36px;
        margin: 0 3px;

        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
}
.chvBox {
  position: absolute;
  top: 70%;
  left: 0;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  .chv-container {
    flex: 1 1 300px;
    min-width: 260px;
    max-width: 400px;

    .chv-item {
      width: 100%;
      height: 200px;
      background-image: url("/images/bgx.png");
      background-size: 100% 100%;
      padding: 5px;
    }
  }
}
</style>
